package org.paybiz.core.payplatform.yeePay.service;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.paybiz.constant.ErrorConstant;
import org.paybiz.core.payplatform.yeePay.ConstantYeePay;
import org.paybiz.core.payplatform.yeePay.bean.SelfTransferResultDO;
import org.paybiz.core.payplatform.yeePay.util.Base64;
import org.paybiz.core.payplatform.yeePay.util.Digest;
import org.paybiz.core.payplatform.yeePay.util.HttpClientUtil;
import org.paybiz.core.payplatform.yeePay.util.MobilePurseSecurityUtils;
import org.paybiz.core.payplatform.yeePay.util.PropTool;
import org.paybiz.util.PayCenterSignature;
import org.paybiz.util.TranslateUtil;
import org.springframework.stereotype.Service;

/**
 * Description:转账实现类
 * @author  LiChunming
 * @version V1.0 
 * @createDateTime：2010-11-4 下午05:57:53 
 * @Company: MSD. 
 * @Copyright: Copyright (c) 2010
 */
@Service("selfTransferService")
public class SelfTransferServiceImpl implements SelfTransferService{
	private static final Logger logger=Logger.getLogger(SelfTransferServiceImpl.class);
	private String customerNumber;
	private String password;
	public SelfTransferServiceImpl(){
		//获取商户号
		customerNumber=PropTool.getValue("p1_MerId_R");
		//获取密码
		
	}
	@Override
	public SelfTransferResultDO SelfTransfer(String requestId,String email,Integer amount) {
		password=PropTool.getValue("p1_pw").trim();
		String keyValue=PropTool.getValue("keyValue_R");
		try {
			this.password=Base64.decode(password);
		} catch (UnsupportedEncodingException e1) {
			 logger.info("Base64解密失败！");
		}
		password=MobilePurseSecurityUtils.secrect(password,keyValue);
		String money=TranslateUtil.getFen2Yuan(amount);
		//构建参数数组
		NameValuePair[] params=new NameValuePair[]{
				new NameValuePair("customerNumber",customerNumber),
				new NameValuePair("requestId",requestId),
				new NameValuePair("password",password),
				new NameValuePair("email",email),
				new NameValuePair("amount",money),
				new NameValuePair("hmac",getSelfTransferHmac(requestId,email,money,keyValue))
		};
		logger.info("URL:"+PropTool.getValue(ConstantYeePay.SelfTransfer_RRL));
		//发送扣费请求，同时得到返回的xml字符串
		String xmlString=HttpClientUtil.getResponseByGet(PropTool.getValue(ConstantYeePay.SelfTransfer_RRL), params);
		logger.info("返回xml：\n"+xmlString);
        String hmac_result="";	//返回来的签名数据
        //解析XML
        logger.info("解析XML：\n");
        SelfTransferResultDO transferResultDO=new SelfTransferResultDO();
        try {
			if(xmlString!=null && !xmlString.trim().equals("")){
				Document document = DocumentHelper.parseText(xmlString);
				Element responseData = document.getRootElement();
				for (Iterator i = responseData.elementIterator(); i.hasNext();) {
					Element element = (Element) i.next();
					logger.info(element.getName() + ":" + element.getText());
					if("customerNumber".equals(element.getName())){
						transferResultDO.setCustomerNumber(element.getText());
					}else if("email".equals(element.getName())){
						transferResultDO.setEmail(element.getText());
					}else if("requestId".equals(element.getName())){
						transferResultDO.setRequestId(element.getText());
					}else if("amount".equals(element.getName())){
						transferResultDO.setAmount(element.getText());
					}else if("externalId".equals(element.getName())){
						transferResultDO.setExternalId(element.getText());
					}else if("result".equals(element.getName())){
						transferResultDO.setResult(element.getText());
					}else if("errMsg".equals(element.getName())){
						transferResultDO.setErrMsg(element.getText());
					}else if("hmac".equals(element.getName())){
						hmac_result=element.getText();
					}
				}
			}
		} catch (Exception e) {
			logger.error("第三方支付返回时解析xml出错,原因："+e.getMessage());
			transferResultDO.setErrMsg("返回时解析xml出错!");
			transferResultDO.setResult("1");
			return transferResultDO;
		}
		//截取xmlString,计算本地接收到的返回结果的hmac
		String hmac_result_locale="";
		if(xmlString.indexOf("</hmac>")>-1){
			xmlString=xmlString.substring(0, xmlString.indexOf("<errMsg>"))+xmlString.substring(xmlString.indexOf("</hmac>")+"</hmac>".length(),xmlString.length());
			xmlString=xmlString.trim();
			hmac_result_locale=Digest.hmacSign(xmlString,keyValue);
			logger.info("本地xml字符串的hmac:"+hmac_result_locale);
		}
		String result = transferResultDO.getResult();
		if(StringUtils.isNotEmpty(result)) {
		    if(transferResultDO.getResult().equals("0")){
	            //判断网络传输的签名与本地签名是否一致
	            if(!hmac_result.equals(hmac_result_locale)){
	                //否则返回失败
	                transferResultDO.setRequestId("1");
	                transferResultDO.setErrMsg("返回验签未通过!");
	                logger.info("签名不一致，查询失败！");
	            }
	        }
		}else {
		    transferResultDO.setResult(ErrorConstant.SYSTEM_ERROR_ID);
            transferResultDO.setErrMsg(ErrorConstant.SYSTEM_ERROR_VALUE);
            logger.info(ErrorConstant.SYSTEM_ERROR_VALUE);
		}
		return transferResultDO;
	}
	private String getSelfTransferHmac(String requestId,String email,String amount,String keyValue){
		StringBuilder aValue=new StringBuilder();
		aValue.append(customerNumber).append(requestId).append(this.password).append(email).append(amount);
		String hmac=PayCenterSignature.hmacSign(aValue.toString(), keyValue);
		return hmac;
	}
}
